<script setup lang="ts">
import {ref, onMounted, computed} from 'vue';
import {useTurnStore} from "@/stores/turn.ts";
import {watch} from 'vue';
import * as echarts from 'echarts';
import {ElMessage} from 'element-plus';
import {RefreshLeft, DataLine, TrendCharts, DataAnalysis, PieChart} from '@element-plus/icons-vue';
import type {Case, kindData} from '@/interface/interface';

const lineChart = ref<HTMLDivElement>();
const store = useTurnStore();
let resizeObserver: ResizeObserver

interface seriesDate {
  name: string,
  type: string,
  data: number[],
  itemStyle: {
    color: echarts.LinearGradientObject | string,
    borderRadius: number[],
    shadowBlur: number,
    shadowColor: string,
    shadowOffsetX: number,
    shadowOffsetY: number,
  },
  label: {
    show: boolean,
    position: string,
    fontSize: number,
    fontWeight: string,
    color: string,
    formatter: string,
  },
  emphasis: {
    itemStyle: {
      shadowBlur: number,
      shadowColor: string,
    }
  }
}

// 现代化配色方案
const colorPalette = [
  ['#667eea', '#764ba2'], // 紫蓝渐变
  ['#f093fb', '#f5576c'], // 粉红渐变
  ['#4facfe', '#00f2fe'], // 蓝青渐变
  ['#43e97b', '#38f9d7'], // 绿青渐变
  ['#fa709a', '#fee140'], // 粉黄渐变
  ['#a8edea', '#fed6e3'], // 青粉渐变
  ['#ff9a9e', '#fecfef'], // 粉色渐变
  ['#ffecd2', '#fcb69f'], // 橙色渐变
];

const getGradientColor = (index: number) => {
  const colors = colorPalette[index % colorPalette.length];
  return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
    { offset: 0, color: colors[0] },
    { offset: 1, color: colors[1] }
  ]);
};

// 计算总案件数和统计信息
const chartStats = computed(() => {
  if (!store.provinceList.length) return null;

  const totalCases = store.provinceList.reduce((total, province) => {
    const provinceData = store.allProvinceData.find(p => p.name === province);
    return total + (provinceData?.value || 0);
  }, 0);

  return {
    totalCases,
    selectedProvinces: store.provinceList.length,
    maxProvinces: 4
  };
});

const reDrawChart = () => {
  if (store.provinceList.length !== 0) {
    if (!lineChart.value?.classList.contains('show')) {
      lineChart.value?.classList.add('show');
    }
  } else {
    lineChart.value?.classList.remove('show');
  }
  if (store.provinceList.length > 4) {
    ElMessage.error('最多只能选择4个省份');
    return;
  }

  // 清理现有图表实例
  if (lineChart.value) {
    const existingChart = echarts.getInstanceByDom(lineChart.value);
    if (existingChart) {
      existingChart.dispose();
    }
  }

  const seriesDate = [] as seriesDate[];
  const getKindData = () => {
    const kindData = [] as kindData[];
    store.allProvinceData.forEach((item) => {
      if (store.provinceList.includes(item.name)) {
        item.data.forEach((data: Case) => {
          const existingKind = kindData.find((kind) => kind.name === data.caseType);
          if (!existingKind) {
            kindData.push({
              name: data.caseType,
              value: [{
                region: item.name,
                value: [data]
              }]
            });
          } else {
            const pro = existingKind.value.find((pro) => pro.region === item.name);
            if (pro) {
              pro.value.push(data)
            } else {
              existingKind.value.push({
                region: item.name,
                value: [data]
              })
            }
          }
        });
      }
    });
    store.provinceEventData = kindData;
    return kindData;
  };

  const kindData = getKindData();

  // 计算总数用于百分比计算
  const totalCasesByType = kindData.map(data => {
    return store.provinceList.reduce((sum, province) => {
      const pro = data.value.find((pro) => pro.region === province);
      return sum + (pro ? pro.value.length : 0);
    }, 0);
  });

  store.provinceList.forEach((item, index) => {
    const data = kindData.map((data) => {
      const pro = data.value.find((pro) => pro.region === item)
      return pro ? pro.value.length : 0;
    });

    seriesDate.push({
      name: item,
      type: 'bar',
      data: data,
      itemStyle: {
        color: getGradientColor(index),
        borderRadius: [0, 4, 4, 0],
        shadowBlur: 6,
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowOffsetX: 1,
        shadowOffsetY: 1,
      },
      label: {
        show: true,
        position: 'right',
        fontSize: 10,
        fontWeight: 'bold',
        color: '#fff',
        distance: 5,
        formatter: (params: any) => {
          const total = totalCasesByType[params.dataIndex];
          const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : '0';
          return `${params.value} (${percentage}%)`;
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 20,
          shadowColor: 'rgba(255, 255, 255, 0.3)',
        }
      }
    });
  });

  if (store.provinceList.length === 0) {
    return;
  }

  const chart = echarts.init(lineChart.value);

  // 优化的图表配置
  chart.setOption({
    backgroundColor: 'transparent',
    animationDuration: 1000,
    animationEasing: 'cubicOut',
    grid: {
      left: '22%',
      right: '8%',
      top: '8%',
      bottom: '5%',
      containLabel: false
    },
    // 全局柱状图配置
    barCategoryGap: '20%',
    barGap: '10%',
    legend: {
      data: store.provinceList,
      top: '2%',
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 11,
        fontWeight: 'bold'
      },
      itemGap: 15,
      icon: 'roundRect',
      itemWidth: 12,
      itemHeight: 12,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: (params: any) => {
        let result = `<div style="font-weight: bold; margin-bottom: 8px; color: #fff;">${params[0].name}</div>`;
        const total = params.reduce((sum: number, item: any) => sum + item.value, 0);

        params.forEach((item: any) => {
          const percentage = total > 0 ? ((item.value / total) * 100).toFixed(1) : '0';
          result += `
            <div style="margin: 4px 0; display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; background: ${item.color}; border-radius: 50%; margin-right: 8px;"></span>
              <span style="flex: 1;">${item.seriesName}: </span>
              <span style="font-weight: bold; color: #fff;">${item.value} 件 (${percentage}%)</span>
            </div>
          `;
        });

        result += `<div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.2); font-weight: bold; color: #67C23A;">总计: ${total} 件</div>`;
        return result;
      }
    },
    xAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisTick: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.8)',
        fontSize: 11
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: kindData.map((item) => item.name),
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.9)',
        fontSize: 12,
        fontWeight: 'bold',
        margin: 10,
        align: 'right',
        verticalAlign: 'middle',
        width: 120,
        overflow: 'truncate',
        interval: 0
      },
      boundaryGap: ['10%', '10%'],
      splitLine: {
        show: false
      }
    },
    series: seriesDate
  });

  chart.on('click', (params) => {
    store.provinceEvent = {
      province: params.seriesName ? params.seriesName : params.name,
      event: params.name
    };
  });
}

watch(store.provinceList, () => {
  console.log(store.provinceList)
  reDrawChart()
});
const clean = () => {
  // 清理现有图表实例
  if (lineChart.value) {
    const existingChart = echarts.getInstanceByDom(lineChart.value);
    if (existingChart) {
      existingChart.dispose();
    }
  }

  store.provinceList.length = 0;
  store.provinceEventData.length = 0;
}

const handleDblClick = () => {
  if(store.turnData === "lineChart"){
    store.turnData = ""
    setTimeout(() => {
      reDrawChart()
    }, 1000)
  }else{
    store.turnData = "lineChart"
    setTimeout(() => {
      reDrawChart()
    }, 500)
  }
}
</script>

<template>
  <div class="chart-container" :class="{active: store.turnData === 'lineChart'}">
    <div class="chart-header">
      <div class="title-section">
        <h4 class="chart-title" @dblclick="handleDblClick">省份案件数量对比分析
          <span @click="handleDblClick" style="padding-top: 10px; transition: all 1s ease;
cursor: pointer;">
        <el-icon><ArrowLeft /></el-icon><el-icon><ArrowRight /></el-icon>
      </span>
        </h4>
        <div v-if="chartStats" class="chart-stats">
          <div class="stat-item">
            <span class="stat-label">已选省份</span>
            <span class="stat-value">{{ chartStats.selectedProvinces }}/{{ chartStats.maxProvinces }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">总案件数</span>
            <span class="stat-value highlight">{{ chartStats.totalCases.toLocaleString() }}</span>
          </div>
        </div>
      </div>
      <el-button type="primary" @click="clean" circle class="refresh-btn">
        <el-icon>
          <RefreshLeft/>
        </el-icon>
      </el-button>
    </div>
    <el-divider class="chart-divider"/>
    <div class="chart-wrapper">
      <div ref="lineChart" class="lineChart"></div>
      <div v-if="!store.provinceList.length" class="empty-state">
        <div class="empty-content">
          <el-icon class="empty-icon"><DataLine /></el-icon>
          <p class="empty-text">点击地图上的省份区域即可查看该省份的案件统计</p>
          <div class="empty-features">
            <div class="feature-item">
              <el-icon><TrendCharts /></el-icon>
              <span>支持多省份对比</span>
            </div>
            <div class="feature-item">
              <el-icon><DataAnalysis /></el-icon>
              <span>实时数据分析</span>
            </div>
            <div class="feature-item">
              <el-icon><PieChart /></el-icon>
              <span>百分比统计</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.chart-container {
  display: flex;
  flex-direction: column;
  width: 21vw;
  height: 98%;
  margin: 0 auto;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
  border-radius: 12px;
  backdrop-filter: blur(12px);
  border: 1.5px solid rgba(255, 255, 255, 0.15);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  position: relative;
  overflow-y: hidden;
  transition: all 1s ease;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  }
}

.chart-header {
  padding: 8px 12px 4px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 4px;
}

.title-section {
  flex: 1;
}

.chart-title {
  margin: 0 0 4px 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #fff 0%, rgba(255, 255, 255, 0.8) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.chart-stats {
  display: flex;
  gap: 16px;
  margin-top: 4px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.stat-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
  font-weight: 500;
}

.stat-value {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 600;

  &.highlight {
    color: #67C23A;
    text-shadow: 0 0 8px rgba(103, 194, 58, 0.3);
  }
}

.refresh-btn {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;

  &:hover {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.15) 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(0);
  }
}

.chart-divider {
  margin: 0 0 8px 0;
  border-color: rgba(255, 255, 255, 0.1);
}

.chart-wrapper {
  position: relative;
  flex: 1;
  min-height: 300px;
  height: calc(100% - 45px);
  padding: 4px 8px 8px 8px;
  overflow: hidden;
}

.lineChart {
  width: 100%;
  height: 100%;
  transition: opacity 0.3s ease;

  &.show {
    opacity: 1;
  }

  &:not(.show) {
    opacity: 0;
  }
}

.empty-state {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
  border-radius: 12px;
  border: 1px dashed rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(8px);
  box-sizing: border-box;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  max-width: 100%;
}

.empty-icon {
  font-size: 40px;
  color: rgba(255, 255, 255, 0.4);
  margin-bottom: 4px;
  animation: pulse 2s infinite;
}

.empty-text {
  margin: 0;
  color: white;
  font-size: 14px;
  font-weight: 600;
  background: linear-gradient(135deg, #fff 0%, rgba(255, 255, 255, 0.8) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.empty-features {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 100%;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  flex: 1;
  min-width: 80px;
  max-width: 120px;

  &:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: translateY(-1px);
  }

  .el-icon {
    font-size: 18px;
    color: #67C23A;
  }

  span {
    font-size: 11px;
    color: rgba(255, 255, 255, 0.8);
    font-weight: 500;
    text-align: center;
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.4;
  }
  50% {
    opacity: 0.8;
  }
}

:deep(.echarts) {
  canvas {
    border-radius: 8px;
  }
}

:deep(.echarts-tooltip) {
  background-color: rgba(0, 0, 0, 0.8) !important;
  border: none !important;
  border-radius: 4px !important;
  padding: 8px 12px !important;

  .tooltip-title {
    color: #fff;
    font-weight: 500;
    margin-bottom: 4px;
  }

  .tooltip-content {
    color: rgba(255, 255, 255, 0.8);
  }
}
.active{
  height: 100vh;
  width: 60vw;
  transform: translate(34%, -50% );
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  span{
    .el-icon{
      transform: rotate(180deg);
    }
  }
}
</style>
